﻿using System.Collections.Generic;
using System.Web.Mvc;

namespace Smarly.Web.Helpers
{
	public static class TagExtensions
	{
		public static MvcTag BeginTag(this HtmlHelper htmlHelper)
		{
			return FormHelper(htmlHelper, "div", new Dictionary<string, object>());
		}
		public static MvcTag BeginTag(this HtmlHelper htmlHelper, IDictionary<string, object> htmlAttributes)
		{
			return FormHelper(htmlHelper, "div", htmlAttributes);
		}

		public static MvcTag BeginTag(this HtmlHelper htmlHelper, string tag)
		{
			return FormHelper(htmlHelper, tag, new Dictionary<string, object>());
		}

		public static MvcTag BeginTag(this HtmlHelper htmlHelper, string tag, object htmlAttributes)
		{
			return FormHelper(htmlHelper, tag, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
		}

		public static MvcTag BeginTag(this HtmlHelper htmlHelper, string tag, IDictionary<string, object> htmlAttributes)
		{
			return FormHelper(htmlHelper, tag, htmlAttributes);
		}

		public static void EndTag(this HtmlHelper htmlHelper, string tag)
		{
			EndTag(htmlHelper.ViewContext, tag);
		}

		internal static void EndTag(ViewContext viewContext, string tag)
		{
			viewContext.Writer.Write("</" + tag + ">");
		}

		private static MvcTag FormHelper(this HtmlHelper htmlHelper, string tag, IDictionary<string, object> htmlAttributes)
		{
			TagBuilder tagBuilder = new TagBuilder(tag);
			tagBuilder.MergeAttributes(htmlAttributes);

			htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
			MvcTag theForm = new MvcTag(htmlHelper.ViewContext, tag);

			return theForm;
		}
	}
}